<?php

namespace app\enterprise\controller;

use app\enterprise\model\disclose\Disclose as DiscloseModel;
use app\enterprise\model\disclose\DiscloseStaff;
use app\enterprise\model\disclose\DiscloseType;
use app\enterprise\model\staff\Staff;
use think\exception\ValidateException;

class Disclose extends Enterprise
{

    public function list()
    {
        $project_name = input('project_name', '');
        $type_id = input('type_id', '');
        $company_id = $this->adminId;
        $page = input('page', 1);
        $size = input('size', 10);
        $userIds = userIds($this->adminId);
        $types = DiscloseType::where('id', '>', 0)->select()->toArray();
        $type_data = array_column($types, 'type_name', 'id');

        $userIds = userIds($this->adminId);
        $where = [];

        $where[] = ['company_id', 'in', $userIds];
        $where[] = [ 'status','=',1];

        $data = DiscloseModel::where('company_id','in', $userIds)->where('status', 1)
            ->when($project_name, function ($query) use ($project_name) {
                $query->where('project_name', 'like', '%' . $project_name . '%');
            })
            ->when($type_id, function ($query) use ($type_id) {
                $query->where('type_id', $type_id);
            })
            ->where($where)
            ->with('user')
            ->order('id', 'desc')
            ->paginate($size)
            ->each(function ($item) use ($type_data) {
                $item->type_name = $type_data[$item->type_id];
                $item->disclose_time = date('Y-m-d H:i:s', $item->disclose_time);
                $staff_ids[] = $item->staff_id;
                $other_staff_ids = json_decode($item->other_staff_ids);
                $staff_ids = array_merge($staff_ids, $other_staff_ids);
                $staffs = Staff::where('id', 'in', $staff_ids)->select()->toArray();
                $staffs = array_column($staffs, null, 'id');

                if (!empty($staffs[$item->staff_id])) {
                    $item->staff_name = $staffs[$item->staff_id]['username'];
                } else {
                    $item->staff_name = '';
                }

                $other_staff_names = '';
                foreach ($other_staff_ids as $other_staff_id) {
                    if (!empty($staffs[$other_staff_id])) {
                        $item->other_staff_names .= $staffs[$other_staff_id]['username'] . ',';
                    }
//                    $other_staff_names .= $staffs[$other_staff_id]['username'] . ',';
                }
                $item->other_staff_names = rtrim($item->other_staff_names, ',');

                // 完成情况
                $complete_status = 0;
                $complete_count = DiscloseStaff::where('disclose_id', $item->id)->where('status', 1)->where('complete_status', 9)->count();
                $total_count = count($other_staff_ids);
                if ($complete_count == $total_count) {
                    $complete_status = 1;
                }
                $item->complete_status = $complete_status;
                $item->comlete_count = $complete_count;
                $item->total_count = $total_count;

                if ( !empty($item->user) ) {
                    $item->company_name = $item->user->company_name;
                    unset($item->user);
                } else {
                    $item->company_name = '未知';
                }

            });

        return app('json')->success([
            'list' => $data->items(),
            'total' => $data->total()
        ]);


    }

    public function save()
    {

        $data = $this->request->only([
            'type_id', 'project_name', 'construction_name', 'supervision_name', 'build_name',
            'overview', 'risk', 'content', 'remark', 'staff_id', 'other_staff_ids', 'disclose_time','type'
        ]);

        $id = input('id', '');


        try {

            validate([
                'type_id|交底分类' => 'require|number',
                'project_name|项目名称' => 'require|max:255',
                'build_name|施工单位'=>'max:255',
                'construction_name|建设单位'=>'max:255',
                'supervision_name|监理单位'=>'max:255',
                'overview|工程概况'=>'require|max:255',
                'risk|现场风险'=>'require|max:255',
                'content|交底内容'=>'require',
                'remark|备注'=>'require|max:255',
                'staff_id|交底人'=>'require|number',
                'other_staff_ids|其他交底人'=>'require|array',
                'type|交底方式'=>'require|number|in:1,2',
                'disclose_time|交底时间'=>'require|dateFormat:Y-m-d H:i:s',
            ])->check($data);

            $data['company_id'] = $this->adminId;
            $data['disclose_time'] = strtotime($data['disclose_time']);
            $data['other_staff_ids'] = json_encode(input('other_staff_ids', []));
            if (empty($id)) {
                // 创建人
                $data['creator_id'] = $this->adminId;
                $res = DiscloseModel::create($data);
                $id = $res->id;
            } else {
                $model = DiscloseModel::getOne($id);
                if (empty($model)) {
                    return app('json')->fail('数据不存在');
                }
                if ($model->company_id != $this->adminId) {
                    return app('json')->fail('无权操作此数据');
                }
                DiscloseModel::update($data, ['id' => $id]);
            }

            $other_staff_ids = array_unique(input('other_staff_ids', []));

            if (empty($other_staff_ids)) {
                // 如果没有其他交底人，则删除
                DiscloseStaff::arrayDelete(['disclose_id' => $id]);
            } else {
                // 如果传入了交底人，则判断是否有其他交底人，如果有，则判断是否有其他交底人中没有此人员，如果有，则删除，如果没有，则添加
                $exist_staffs = DiscloseStaff::where('disclose_id', $id)->where('status', 1)->select()->toArray();
                if (empty($exist_staffs)) {
                    foreach ($other_staff_ids as $staff_id) {
                        $staff = DiscloseStaff::create([
                            'disclose_id' => $id,
                            'staff_id' => $staff_id,
                            'status' => 1
                        ]);
                    }
                } else {
                    foreach ($exist_staffs as $exist_staff) {
                        if (!in_array($exist_staff['staff_id'], $other_staff_ids)) {
                            // 如果传入的其他交底人中没有此人员，则删除
                            DiscloseStaff::dataDelete($exist_staff['id']);
                        }
                    }
                    $exist_ids = array_column($exist_staffs, 'staff_id');
                    foreach ($other_staff_ids as $staff_id) {
                        if (!in_array($staff_id, $exist_ids)) {
                            // 如果传入的其他交底人中没有此人员，则添加
                            DiscloseStaff::create([
                                'disclose_id' => $id,
                                'staff_id' => $staff_id,
                                'status' => 1
                            ]);
                        }
                    }
                }
            }
            return app('json')->success('操作成功');
        } catch (ValidateException $e) {
            return app('json')->fail($e->getMessage());
        }

    }

    public function info()
    {

        $id = input('id', '');

        if (empty($id)) {
            return app('json')->fail('参数错误');
        }

        $model = DiscloseModel::getOne($id);

        if (empty($model)) {
            return app('json')->fail('数据不存在');
        }

        if ($model->company_id != $this->adminId) {
            return app('json')->fail('无权操作此数据');
        }

        $staff = Staff::getOne($model->staff_id);
        if (!empty($staff)) {
            $model->staff_name = $staff->username;
        } else {
            $model->staff_name = '';
        }


        $type = DiscloseType::getOne($model->type_id);

        $model->type_name = $type->type_name;

        $other_staff_ids = json_decode($model->other_staff_ids);

        // 完成情况
        $complete_status = 0;
        $complete_count = DiscloseStaff::where('disclose_id', $model->id)->where('status', 1)->where('complete_status', 9)->count();
        $total_count = count($other_staff_ids);
        if ($complete_count == $total_count) {
            $complete_status = 1;
        }
        $model->complete_status = $complete_status;
        $model->comlete_count = $complete_count;
        $model->total_count = $total_count;
        $model->disclose_time = date('Y-m-d H:i:s', $model->disclose_time);

        return app('json')->success([
            'data'=>$model,
        ]);

    }

    public function staffs()
    {

        $id = input('id', '');

        if (empty($id)) {
            return app('json')->fail('参数错误');
        }
        $model = DiscloseModel::getOne($id);
        if (empty($model)) {
            return app('json')->fail('数据不存在');
        }
        if ($model->company_id != $this->adminId) {
            return app('json')->fail('无权操作此数据');
        }
        $page = input('page', 1);
        $size = input('size', 10);
        $staffs = DiscloseStaff::where('disclose_id', $id)
            ->where('status', 1)->page($size)
            ->paginate($size)
            ->each(function ($item) {
                $staff = Staff::getOne($item->staff_id);
                $item->staff_name = $staff->username;
                if ($item->complete_time) {
                    $item->complete_time = date('Y-m-d H:i:s', $item->complete_time);
                } else {
                    $item->complete_time = '';
                }
            });

        return app('json')->success([
            'list'=>$staffs->items(),
            'total'=>$staffs->total(),
            'total_page'=>$staffs->lastPage(),
        ]);
    }


    public function nullify()
    {
        $id = input('id', '');
        if (empty($id)) {
            return app('json')->fail('参数错误');
        }
        $model = DiscloseModel::getOne($id);
        if (empty($model)) {
            return app('json')->fail('数据不存在');
        }
        if ($model->company_id != $this->adminId) {
            return app('json')->fail('无权操作此数据');
        }

        DiscloseModel::update(['disclose_status'=>9], ['id'=>$id]);

        return app('json')->success('操作成功');

    }


    public function getDiscloseAutographs()
    {
        $id = input('id', '');
        if (empty($id)) {
            return app('json')->fail('参数错误');
        }

        $disclose = DiscloseModel::getOne($id);

        if (empty($disclose)) {
            return app('json')->fail('数据不存在');
        }
        if ($disclose->company_id != $this->adminId) {
            return app('json')->fail('无权操作此数据');
        }


        $staffs = DiscloseStaff::where('disclose_id', $id)->where('status', 1)
            ->where('complete_status', 9)
            ->select()->toArray();

        // 被交底人签名
        $data = [];
        // 交底人签名
        $staff_sign = '';

        foreach ($staffs as $staff) {
            $data[] = $staff['img_url'];
        }

        return app('json')->success([
            'staff_sign'=>$staff_sign,
            'other_staff_signs'=>$data,
        ]);

    }




}